package com.example.demo.controller;

import com.example.demo.dao.ClassMemberDao;
import com.example.demo.dao.HomeworkDao;
import com.example.demo.dao.HomeworkQuestionDao;
import com.example.demo.dao.HomeworkSubmissionDao;
import com.example.demo.dao.UserDao;
import com.example.demo.entity.pojo.ClassMember;
import com.example.demo.entity.pojo.Homework;
import com.example.demo.entity.pojo.HomeworkQuestion;
import com.example.demo.entity.pojo.HomeworkSubmission;
import com.example.demo.entity.pojo.User;
import com.example.demo.entity.dto.TokenUserDto;
import com.example.demo.entity.vo.ResponseVO;
import com.example.demo.entity.vo.HomeworkDetailVO;
import com.example.demo.entity.vo.HomeworkListVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 作业管理控制器
 */
@RestController
@RequestMapping("/homework")
public class HomeworkController extends BaseController {

    @Autowired
    private HomeworkDao homeworkDao;

    @Autowired
    private ClassMemberDao classMemberDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private HomeworkQuestionDao homeworkQuestionDao;

    @Autowired
    private HomeworkSubmissionDao homeworkSubmissionDao;

    /**
     * 查询我的作业
     * 根据用户所在的班级查询作业
     *
     * @param request HTTP请求对象，用于获取用户token
     * @return 响应结果，包含作业列表和教师姓名
     */
    @GetMapping("/getMyHomework")
    public ResponseVO<List<HomeworkListVO>> getMyHomework(HttpServletRequest request) {
        try {
            // 验证用户登录状态
            TokenUserDto tokenUserDto = getTokenUserDto(request);
            if (tokenUserDto == null) {
                return getFail("登录超时，请重新登录！");
            }

            // 查询用户加入的所有班级
            List<ClassMember> memberList = classMemberDao.queryByUserId(tokenUserDto.getUserId());

            if (memberList.isEmpty()) {
                return getSuccess("您还没有加入任何班级，暂无作业！", new ArrayList<>());
            }

            // 提取班级ID列表
            List<Integer> classIds = new ArrayList<>();
            for (ClassMember member : memberList) {
                classIds.add(member.getClassId());
            }

            // 根据班级ID列表查询作业
            List<Homework> homeworkList = homeworkDao.queryByClassIds(classIds);

            // 构建包含教师姓名的作业列表VO
            List<HomeworkListVO> homeworkListVOs = new ArrayList<>();
            for (Homework homework : homeworkList) {
                // 查询教师信息
                User teacher = userDao.queryById(homework.getTeacherId());
                String teacherName = (teacher != null) ? teacher.getUsername() : "未知教师";

                // 创建作业列表VO
                HomeworkListVO homeworkVO = new HomeworkListVO(homework, teacherName);
                homeworkListVOs.add(homeworkVO);
            }

            return getSuccess("获取我的作业列表成功！", homeworkListVOs);

        } catch (Exception e) {
            return getFail("系统错误：" + e.getMessage());
        }
    }

    /**
     * 获取作业详情
     *
     * @param request HTTP请求对象，用于获取用户token
     * @param homeworkId 作业ID
     * @return 响应结果，包含作业详情和教师姓名
     */
    @GetMapping("/getHomeworkDetail")
    public ResponseVO<HomeworkDetailVO> getHomeworkDetail(HttpServletRequest request,
                                                         @RequestParam Integer homeworkId) {
        try {
            // 验证用户登录状态
            TokenUserDto tokenUserDto = getTokenUserDto(request);
            if (tokenUserDto == null) {
                return getFail("登录超时，请重新登录！");
            }

            // 参数验证
            if (homeworkId == null) {
                return getFail("作业ID不能为空！");
            }

            // 查询作业详情
            Homework homework = homeworkDao.queryById(homeworkId);
            if (homework == null) {
                return getFail("作业不存在！");
            }

            // 验证用户是否有权限查看该作业（检查是否在对应班级中）
            ClassMember member = classMemberDao.queryByClassIdAndUserId(
                homework.getClassId(), tokenUserDto.getUserId());
            if (member == null) {
                return getFail("您没有权限查看该作业！");
            }

            // 查询教师信息
            User teacher = userDao.queryById(homework.getTeacherId());
            String teacherName = (teacher != null) ? teacher.getUsername() : "未知教师";

            // 构建作业详情VO
            HomeworkDetailVO homeworkDetail = new HomeworkDetailVO(homework, teacherName);

            return getSuccess("获取作业详情成功！", homeworkDetail);

        } catch (Exception e) {
            return getFail("系统错误：" + e.getMessage());
        }
    }

    /**
     * 根据班级查询作业
     *
     * @param request HTTP请求对象，用于获取用户token
     * @param classId 班级ID
     * @return 响应结果，包含作业列表和教师姓名
     */
    @GetMapping("/getHomeworkByClass")
    public ResponseVO<List<HomeworkListVO>> getHomeworkByClass(HttpServletRequest request,
                                                              @RequestParam Integer classId) {
        try {
            // 验证用户登录状态
            TokenUserDto tokenUserDto = getTokenUserDto(request);
            if (tokenUserDto == null) {
                return getFail("登录超时，请重新登录！");
            }

            // 参数验证
            if (classId == null) {
                return getFail("班级ID不能为空！");
            }

            // 验证用户是否在该班级中
            ClassMember member = classMemberDao.queryByClassIdAndUserId(
                classId, tokenUserDto.getUserId());
            if (member == null) {
                return getFail("您不是该班级的成员，无法查看作业！");
            }

            // 查询班级作业
            List<Homework> homeworkList = homeworkDao.queryByClassId(classId);

            // 构建包含教师姓名的作业列表VO
            List<HomeworkListVO> homeworkListVOs = new ArrayList<>();
            for (Homework homework : homeworkList) {
                // 查询教师信息
                User teacher = userDao.queryById(homework.getTeacherId());
                String teacherName = (teacher != null) ? teacher.getUsername() : "未知教师";

                // 创建作业列表VO
                HomeworkListVO homeworkVO = new HomeworkListVO(homework, teacherName);
                homeworkListVOs.add(homeworkVO);
            }

            return getSuccess("获取班级作业列表成功！", homeworkListVOs);

        } catch (Exception e) {
            return getFail("系统错误：" + e.getMessage());
        }
    }

    /**
     * 获取作业题目（学生版，不显示答案和解析）
     *
     * @param request HTTP请求对象，用于获取用户token
     * @param homeworkId 作业ID
     * @return 响应结果，包含题目列表
     */
    @GetMapping("/getHomeworkQuestions")
    public ResponseVO<List<HomeworkQuestion>> getHomeworkQuestions(HttpServletRequest request,
                                                                  @RequestParam Integer homeworkId) {
        try {
            // 验证用户登录状态
            TokenUserDto tokenUserDto = getTokenUserDto(request);
            if (tokenUserDto == null) {
                return getFail("登录超时，请重新登录！");
            }

            // 参数验证
            if (homeworkId == null) {
                return getFail("作业ID不能为空！");
            }

            // 查询作业信息
            Homework homework = homeworkDao.queryById(homeworkId);
            if (homework == null) {
                return getFail("作业不存在！");
            }

            // 验证用户是否有权限查看该作业
            ClassMember member = classMemberDao.queryByClassIdAndUserId(
                homework.getClassId(), tokenUserDto.getUserId());
            if (member == null) {
                return getFail("您没有权限查看该作业！");
            }

            // 检查用户角色，决定返回哪个版本的题目
            User user = userDao.queryById(tokenUserDto.getUserId());
            List<HomeworkQuestion> questions;

            if ("teacher".equals(user.getRole()) && homework.getTeacherId().equals(tokenUserDto.getUserId())) {
                // 如果是出题教师，返回完整版本（包含答案和解析）
                questions = homeworkQuestionDao.queryByHomeworkIdForTeacher(homeworkId);
            } else {
                // 如果是学生，检查是否已提交作业
                HomeworkSubmission submission = homeworkSubmissionDao.queryByHomeworkAndStudent(
                    homeworkId, tokenUserDto.getUserId());

                if (submission != null && "graded".equals(submission.getStatus())) {
                    // 已提交且已批改，可以查看答案和解析
                    questions = homeworkQuestionDao.queryByHomeworkIdForTeacher(homeworkId);
                } else {
                    // 未提交或未批改，不显示答案和解析
                    questions = homeworkQuestionDao.queryByHomeworkIdForStudent(homeworkId);
                }
            }

            return getSuccess("获取作业题目成功！", questions);

        } catch (Exception e) {
            return getFail("系统错误：" + e.getMessage());
        }
    }

    /**
     * 提交作业
     *
     * @param request HTTP请求对象，用于获取用户token
     * @param homeworkId 作业ID
     * @param answers 学生答案（JSON格式：[{"questionId":1,"answer":"A"},{"questionId":2,"answer":"B"}]）
     * @return 响应结果
     */
    @PostMapping("/submitHomework")
    public ResponseVO<String> submitHomework(HttpServletRequest request,
                                           @RequestParam Integer homeworkId,
                                           @RequestParam String answers) {
        try {
            // 验证用户登录状态
            TokenUserDto tokenUserDto = getTokenUserDto(request);
            if (tokenUserDto == null) {
                return getFail("登录超时，请重新登录！");
            }

            // 参数验证
            if (homeworkId == null) {
                return getFail("作业ID不能为空！");
            }
            if (StringUtils.isBlank(answers)) {
                return getFail("答案不能为空！");
            }

            // 查询作业信息
            Homework homework = homeworkDao.queryById(homeworkId);
            if (homework == null) {
                return getFail("作业不存在！");
            }

            // 验证用户是否有权限提交该作业
            ClassMember member = classMemberDao.queryByClassIdAndUserId(
                homework.getClassId(), tokenUserDto.getUserId());
            if (member == null) {
                return getFail("您没有权限提交该作业！");
            }

            // 检查是否已经提交过
            HomeworkSubmission existingSubmission = homeworkSubmissionDao.queryByHomeworkAndStudent(
                homeworkId, tokenUserDto.getUserId());
            if (existingSubmission != null) {
                return getFail("您已经提交过该作业了！");
            }

            // 检查是否超过截止时间
            if (homework.getDeadline() != null && new Date().after(homework.getDeadline())) {
                return getFail("作业提交时间已过！");
            }

            // 解析学生答案
            List<Map<String, Object>> answerList;
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                answerList = objectMapper.readValue(answers, List.class);
            } catch (Exception e) {
                return getFail("答案格式错误！");
            }

            // 自动批改并计算分数
            String result = autoGradeHomework(homeworkId, tokenUserDto.getUserId(), answerList);

            return getSuccess(result, null);

        } catch (Exception e) {
            return getFail("系统错误：" + e.getMessage());
        }
    }

    /**
     * 自动批改作业
     *
     * @param homeworkId 作业ID
     * @param studentId 学生ID
     * @param answerList 学生答案列表
     * @return 批改结果信息
     */
    private String autoGradeHomework(Integer homeworkId, String studentId, List<Map<String, Object>> answerList) {
        try {
            // 查询作业题目
            List<HomeworkQuestion> questions = homeworkQuestionDao.queryByHomeworkId(homeworkId);

            // 创建提交记录
            HomeworkSubmission submission = new HomeworkSubmission();
            submission.setHomeworkId(homeworkId);
            submission.setStudentId(studentId);
            submission.setSubmitTime(new Date());
            submission.setStatus("submitted");
            submission.setTotalScore(BigDecimal.ZERO);

            int submissionResult = homeworkSubmissionDao.insert(submission);
            if (submissionResult <= 0) {
                throw new RuntimeException("创建提交记录失败");
            }

            // 批改每道题目
            BigDecimal totalScore = BigDecimal.ZERO;
            int correctCount = 0;

            for (Map<String, Object> answerMap : answerList) {
                Integer questionId = (Integer) answerMap.get("questionId");
                String studentAnswer = (String) answerMap.get("answer");

                // 查找对应的题目
                HomeworkQuestion question = null;
                for (HomeworkQuestion q : questions) {
                    if (q.getId().equals(questionId)) {
                        question = q;
                        break;
                    }
                }

                if (question == null) {
                    continue; // 跳过无效题目
                }

                // 判断答案是否正确
                boolean isCorrect = false;
                BigDecimal questionScore = BigDecimal.ZERO;

                if (StringUtils.isNotBlank(studentAnswer) && StringUtils.isNotBlank(question.getCorrectAnswer())) {
                    // 简单的字符串比较（忽略大小写和空格）
                    String correctAnswer = question.getCorrectAnswer().trim().toUpperCase();
                    String studentAnswerTrimmed = studentAnswer.trim().toUpperCase();

                    if (correctAnswer.equals(studentAnswerTrimmed)) {
                        isCorrect = true;
                        questionScore = question.getScore();
                        correctCount++;
                    }
                }

                totalScore = totalScore.add(questionScore);
            }

            // 更新提交记录的总分和状态
            submission.setTotalScore(totalScore);
            submission.setStatus("graded"); // 自动批改完成
            homeworkSubmissionDao.update(submission);

            return String.format("作业提交成功！总分：%.2f分，正确题数：%d/%d",
                totalScore.doubleValue(), correctCount, questions.size());

        } catch (Exception e) {
            throw new RuntimeException("自动批改失败：" + e.getMessage());
        }
    }
}
